package fr.upmc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.jasper.tagplugins.jstl.core.ForEach;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import fr.upmc.bean.Address;
import fr.upmc.bean.Contact;
import fr.upmc.bean.ContactGroup;
import fr.upmc.bean.Enterprise;
import fr.upmc.bean.PhoneNumber;
import fr.upmc.dao.ContactDAO;
import fr.upmc.utils.HibernateUtils;
import fr.upmc.utils.SessionTracker;

public class NewContact extends HttpServlet {

	private static final long serialVersionUID = -3453344416053988923L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {

		//if user not connected, get him the hell out of here
		if(!SessionTracker.isUserConnected(request))
		{
			SessionTracker.redirectToHome(response);
		}
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		Session session = HibernateUtils.getSessionFactory().openSession();

		// === Contact
		Contact contact;// = new Contact();

		if(request.getParameter("ent") != null){
			System.err.println("DAMN");
			contact = new Enterprise();
			String siret = request.getParameter("ns");
			try {
				((Enterprise)contact).setNumSiret(Long.parseLong(siret));
			} catch (Exception e) {
				out.print("failure");
				return;
			}
		}
		else
			contact = new Contact();
		
		String firstName = request.getParameter("firstname");
		String lastName = request.getParameter("lastname");
		String email = request.getParameter("email");

		if(firstName == null || lastName == null || email == null || firstName.length()<1 || lastName.length()<1 || email.length()<1)
		{
			out.print("failure");
			return;
		}
		
		contact.setFirstName(firstName);
		contact.setLastName(lastName);
		contact.setEmail(email);

		// === Address
		Address address = new Address();

		String street = request.getParameter("street");
		String city = request.getParameter("city");
		String zip = request.getParameter("zip");
		String country = request.getParameter("country");

		address.setStreet(street);
		address.setCity(city);
		address.setZip(zip);
		address.setCountry(country);

		if(!(street.equals("") && city.equals("") && zip.equals("") && country.equals("")))
			contact.setAddress(address);

		// === Phone number
		PhoneNumber phoneNumber1 = new PhoneNumber();
		PhoneNumber phoneNumber2 = new PhoneNumber();
		PhoneNumber phoneNumber3 = new PhoneNumber();

		String phone1 = request.getParameter("pn1");
		String phone2 = request.getParameter("pn2");
		String phone3 = request.getParameter("pn3");

		phoneNumber1.setPhoneNumber(phone1);
		phoneNumber1.setPhoneKind("Mobile");

		phoneNumber2.setPhoneNumber(phone2);
		phoneNumber2.setPhoneKind("Office");

		phoneNumber3.setPhoneNumber(phone3);
		phoneNumber3.setPhoneKind("Home");

		contact.addProfiles(phoneNumber1);
		phoneNumber1.setContact(contact);

		contact.addProfiles(phoneNumber2);
		phoneNumber2.setContact(contact);

		contact.addProfiles(phoneNumber3);
		phoneNumber3.setContact(contact);

		String cg = request.getParameter("cg");
		String[] groups = cg.split(",");
		
		Set<String> set = new HashSet<String>(); 
		
		ContactGroup contactGroup = null;
		
		for (String s : groups) {
			set.add(s.trim());
		}
		
		//HQL restrictions
		for (String s : set) {
			contactGroup = (ContactGroup)session.createCriteria(ContactGroup.class)
                    .add(Restrictions.eq("groupName", s.trim()))
                    .uniqueResult();
			
			if(contactGroup == null){
				contactGroup = new ContactGroup();
			}
			
			contactGroup.addContacts(contact);
			contactGroup.setGroupName(s.trim());

			contact.addBook(contactGroup);
		}

		// === Create a contact
		ContactDAO daoContact = new ContactDAO(session);
		daoContact.create(contact);

		// === Response
		//response.setContentType("text/html");


		//out.println("<html><body>");
		//out.println("<h2>Contact " + firstName + " " + lastName + " ajouté !</h2>");
		//out.println("</body></html>");
		out.print("success");
		out.close();
		session.close();

		return;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {

		doGet(request,response);

		return;
	}
}
